<template>
  <div v-if="userToken" class="container">
    <template v-if="cartList.cartInfoList.length">
      <div style="margin-bottom: 100px">
        <div class="goods-items" v-for="(item, index) in cartList.cartInfoList" :key="index">
          <div class="left">
            <van-checkbox
              v-model:model-value="item.isChecked"
              checked-color="#ee0a24"
              data-goodsId="{{ item.skuId }}"
              data-index="{{ index }}"
              @change="updateStatus(item.skuId, item.isChecked, index)"
            ></van-checkbox>
          </div>

          <div class="mid">
            <img :src="item.imgUrl" />
            <van-icon size="14px" name="warning-o">不可用券</van-icon>
          </div>

          <div class="right">
            <div class="title">{{ item.skuName }}</div>

            <div class="buy">
              <div class="price">
                <div class="symbol">￥</div>
                <div class="num">{{ item.cartPrice }}</div>
              </div>
              <van-icon size="18px" color="#71797f" name="delete" @click="delCart(item.skuId)" />
              <div class="buy1">
                <van-stepper
                  v-model="item.skuNum"
                  @change="updateCount(item.skuNum, item.skuId, index)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <div v-else class="goods-zero">
      <img src="../../../static/images/GoodsZero.png" style="width: 300px" />
      <div>去添加购物车</div>
    </div>

    <!-- 底部工具栏 -->
    <van-submit-bar
      :price="allPrice * 100"
      button-text="去结算"
      @submit="toOrder"
      :disabled="allPrice === 0"
    >
      <van-checkbox v-model:model-value="selectAllStatus" checked-color="#FA4126">
        全选
      </van-checkbox>
    </van-submit-bar>
  </div>

  <div v-else class="unLogin">
    <div>
      <img style="width: 200px" src="../../../static/images/unLogin.png" />
    </div>
    <div>
      <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" to="NoLogin"
        >尚未登录，前去登录</van-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { reqCartList, reqCheckCart, reqBatchCheckCart, reqUpdateNum, reqDelCart } from '@/api/cart'
import { reactive } from 'vue'
import type { ICartList } from '@/types/cart'
import router from '@/router'
import { getStorage } from '@/utils/storage'

// 获取token
let userToken = getStorage()

// 初始化数据
const cartList = reactive<ICartList>({
  cartInfoList: []
})

//#region 获取购物车列表数据
// 数据备份--之后做步进器数据更改的时候用
interface oldCartItem {
  skuId: number
  skuNum: number
}
const oldArr = ref<oldCartItem[]>([])

const getOldCartList = () => {
  cartList.cartInfoList.forEach((item) => {
    const idNum = {
      skuId: item.skuId,
      skuNum: item.skuNum
    }
    oldArr.value?.push(idNum)
  })
}

const getCartList = async () => {
  const res = await reqCartList()
  if (res.code === 200) {
    const { cartInfoList } = res.data[0]
    cartList.cartInfoList = cartInfoList
    getOldCartList()
  }
}

onMounted(async () => {
  if (userToken) {
    await getCartList()
  }
  // console.log('---', oldArr.value)
  // console.log(userToken)
})
//#endregion

//#region 更新购物车商品的状态
const updateStatus = async (id: number, isChecked: number | string, index: number) => {
  // 接收商品的id
  isChecked = isChecked ? 1 : 0
  // console.log(isChecked)

  const res = await reqCheckCart(id, isChecked)
  if (res.code === 200) {
    // console.log(index)

    cartList.cartInfoList[index].isChecked = isChecked
  }
}

// const updateStatus = (event: any) => {
//   // 接收商品的id
//   const { goodsId, index } = event.target.dataset
//   // 获取最新的状态 true 和 false
//   const isChecked = event.detail ? 1 : 0
//   console.log(goodsId, index, isChecked)
// }
// #endregion

//#region 全选和全不选
// const selectAll = async (event: boolean) => {
//   // 处理选中的状态
//   // console.log('---'+event);
//   const isChecked = event ? 1 : 0
//   // 准备skuIdList数组
//   const skuIdList: number[] = []
//   cartList.cartInfoList.forEach((item) => skuIdList.push(item.skuId))
//   // 传递参数，发送请求
//   const res = await reqBatchCheckCart(isChecked, skuIdList)
//   if (res.code === 200) {
//     // 在请求成功以后，更新本地的数据
//     cartList.cartInfoList.forEach((item) => {
//       item.isChecked = isChecked ? 1 : 0
//     })
//   }
// }

const selectAllStatus = computed({
  get() {
    return (
      cartList.cartInfoList.every((item) => item.isChecked) && cartList.cartInfoList.length !== 0
    )
  },
  async set(v) {
    const newValue = v ? 1 : 0
    // console.log(value)
    let skuIdList: number[] = []
    cartList.cartInfoList.forEach((item) => {
      skuIdList.push(item.skuId)
    })
    let res = await reqBatchCheckCart(newValue, skuIdList)
    if (res.code === 200) {
      cartList.cartInfoList.forEach((item) => (item.isChecked = newValue))
    }
  }
})
//#endregion

//#region 计算总金额
const allPrice = computed(() => {
  let allPrice = 0
  cartList.cartInfoList.forEach((item) => {
    // 如果商品的isChecked属性等于 1，说明该商品被选中
    if (item.isChecked === 1) {
      allPrice += item.skuNum * item.cartPrice
    }
  })
  return allPrice
})
//#endregion

//#region 更新购买数量 + 防抖
let timeId = 0
const updateCount = async (value: number, id: number, index: number) => {
  clearTimeout(timeId)
  timeId = setTimeout(async () => {
    let oldNum = 0
    oldArr.value.forEach((item) => {
      if (item.skuId === id) {
        oldNum = item.skuNum
      }
    })
    const skuId = id.toString()
    // 计算差值 传给服务器
    const skuNum = (value - oldNum).toString()
    const res = await reqUpdateNum(skuId, skuNum)
    if (res.code === 200) {
      getCartList()
      cartList.cartInfoList[index].skuNum = value
    }
  }, 300)
}
//#endregion

//#region 跳转到支付页面
const toOrder = () => {
  router.push('/orderPay')
}
//#endregion

//#region 删除单个商品
const delCart = async (skuId: number) => {
  const id = skuId.toString()
  const res = await reqDelCart(id)
  if (res.code === 200) {
    await getCartList()
  }
}
//#endregion
</script>
<script lang="ts">
export default {
  name: 'CartComponent'
}
</script>

<style lang="less" scoped>
.unLogin {
  display: flex;
  margin-top: 150px;
  margin-left: 80px;
  width: 200px;
  justify-content: center;
  flex-wrap: wrap;
}
.container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #f3f3f3;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  padding-top: 0.5rem;
}
.goods-items {
  display: flex;
  align-items: center;
  padding: 15px 10px;
  border-radius: 16px;
  margin: 10px 10px;
  background-color: white;
  box-sizing: border-box;
}
.goods-items .left {
  display: flex;
  align-items: center;
  justify-content: center;
}
.goods-items .mid {
  width: 100px;
  height: 90px;
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 5px;
  margin-left: 5px;
}
.mid img {
  height: 100%;
  padding-bottom: 5px;
}
.goods-items .right {
  height: 125px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-left: 10px;
}
.right .title {
  flex: 1;
  flex-shrink: 0;
  font-size: 14px;
  color: #333;
  font-weight: 400;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
}
.buy {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.price {
  display: flex;
  color: #fa4126;
  font-size: 20px;
}
.price .symbol {
  font-size: 10px;
  margin-right: 2px;
  margin-top: 8px;
}
.van-submit-bar {
  bottom: 50px !important;
}
.delete-button {
  height: 100%;
}
.goods-zero {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  font-size: 18px;
  flex-wrap: wrap;
  justify-content: center;
  position: absolute;
  top: 20%;
  color: #515050;
}
</style>
